package org.bigtree.example.common.webapi;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.Data;
import org.springframework.beans.BeanUtils;

import java.util.Collection;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author bigTree
 * @since 2025/4/24
 */
@Data
public class PageResult<E>  {
    private Long pageNo;
    private Integer pageSize;
    private long total;
    private long pages;
    private int count;
    private Collection<E> records;

    public final static PageResult<?> EMPTY = new PageResult<>();
    static {
        EMPTY.setPageNo(1L);
        EMPTY.setPageSize(Integer.MAX_VALUE);
        EMPTY.setTotal(0L);
        EMPTY.setPages(0L);
        EMPTY.setCount(0);
        EMPTY.setRecords(List.of());
    }


    public static <R> PageResult<R> of(IPage<R> page) {
        PageResult<R> pageResult = new PageResult<>();
        BeanUtils.copyProperties(page, pageResult);
        pageResult.setPageNo(page.getCurrent());
        pageResult.setPageSize((int)page.getSize());
        pageResult.setCount(page.getRecords().size());
        return pageResult;
    }

    public static <U, R> PageResult<R> of(IPage<U> page, Function<U, R> convert) {
        PageResult<R> pageResult = new PageResult<>();
        BeanUtils.copyProperties(page, pageResult);
        pageResult.setPageNo(page.getCurrent());
        pageResult.setPageSize((int)page.getSize());
        List<U> records = page.getRecords();
        pageResult.setCount(records.size());
        pageResult.setRecords(records.stream().map(convert).collect(Collectors.toList()));
        return pageResult;
    }
}
